#include <QtCore/QCoreApplication>
#include <QtCore/QFile>
#include <QtCore/QDir>
#include <QDebug>
#include "core.h"

#include <unistd.h>
#include <sys/stat.h>


void daemonOutput(QtMsgType type, const char *msg)
{
    QFile output("/tmp/vibrateme.log");
    if( !output.open( QIODevice::Append))
        return;

    switch (type) {
    case QtDebugMsg:
    case QtWarningMsg:
    case QtCriticalMsg:
    case QtFatalMsg:
        output.write(msg);
        output.write("\n");
    break;
    default:;
    }

    output.close();
}

int main(int argc, char *argv[])
{
    //Process ID
    pid_t pid;

    //Fork off the parent process
    pid = fork();
    if( pid < 0) {
        exit(EXIT_FAILURE);
    }

    //If we got a good PID, then we can exit the parent process
    if( pid > 0) {
        exit(EXIT_SUCCESS);
    }

    // Change the file mode mask (just in case if we plan to use filesystem
    umask(0);

    //Logs for writing
    qInstallMsgHandler(daemonOutput);
    QCoreApplication app(argc, argv);

    QFile pidFile("/var/run/vibrateme/pid");
    if( pidFile.exists())
    {
        //Do not allow running multiple instances
        qDebug() << "PID file already exists exiting second instance";
        exit(EXIT_FAILURE);
    }

    QDir dir;
    dir.mkpath("/var/run/vibrateme");

    if( pidFile.open( QIODevice::WriteOnly))
    {
        pid_t ownPid = getpid();
        pidFile.write( QByteArray::number( ownPid));
        pidFile.close();
    }
    else
    {
        qDebug() << "unable to create \"pid\" file";

        //Do not allow running multiple instances
        exit(EXIT_FAILURE);
    }

    //New Session ID
    pid_t sid = setsid();

    if (sid < 0) {
        qDebug() << "unable to get new SID";
        exit(EXIT_FAILURE);
    }

    //Change the current working directory
    if( (chdir("/")) < 0) {
        qDebug() << "unable to change current dirrectory to: \"/\"";
        exit(EXIT_FAILURE);
    }

    // Close out the standard file descriptors
    close(STDIN_FILENO);
    close(STDOUT_FILENO);
    close(STDERR_FILENO);

    //Creating Core
    Core core;
    if(!core.initialize())
    {
        qDebug() << "unable to initialize core";
        exit(EXIT_FAILURE);
    }

    int ret = app.exec();

    if( !pidFile.remove())
    {
        qDebug() << "unable to remove PID file";
    }

    return ret;
}
